
<template>
  <div style="display: flex" class="tempxyz menmuStyle">
    <CCard class="rightCard">
      <CCardHeader class="header-wraper">
        <div class="header-left-titleWraper">
          <span class="textTitle">服务管理</span>
        </div>
        <div class="header-right-wraper">
          <Input
            v-model="name"
            placeholder="请输入关键字"
            style="width: 200px"
            class="headerMar"
          />
          <Button
            type="primary"
            @click="searchList"
            class="system-btn-style headerMar"
            style="margin-right: 10px"
          >
            <Icon type="ios-search" />&nbsp;查询
          </Button>
          <Button
            type="warning"
            @click="addServe"
            class="system-btn-style headerMar"
          >
            <i class="fa fa-plus" aria-hidden="true"></i>&nbsp;添加
          </Button>
        </div>
      </CCardHeader>


      <CCardBody class="card-body">
        <div style="height: calc(100% - 46px)">
          <TableList ref="table" :getColumn="getColumns" :getAxios="getAxios">
            <template v-slot:type="item">
              {{ item.data.row.clusterServiceType.description }}
            </template>
            <template v-slot:resources="item">
              {{ getResources(item.data.row, "resources", "resourceAlias") }}
            </template>
            <template v-slot:relations="item">
              {{ getResources(item.data.row, "relations", "serviceName") }}
            </template>
            <template v-slot:show_details="item">
              <CButton
                title="编辑"
                variant="outline"
                class="textBtnStyle onButton system-btn-style"
                @click="changeServe(item.data.row)"
                >修改</CButton
              >
              <CButton
                title="编辑"
                variant="outline"
                class="textBtnStyle onButton system-btn-style"
                @click="delectRow(item.data.row)"
                >删除</CButton
              >
            </template>
          </TableList>
        </div>
      </CCardBody>
    </CCard>




    <!--创建接点-->
    <Modal v-model="checkTask" draggable scrollable :width="600">
      <p slot="header" class="modalHeader">
        <!-- <img src="@/assets/icons/search.png" alt />-->
        <span style="margin-left: 5px">{{
          formItem.id ? "更新服务" : "创建服务"
        }}</span>
      </p>
      <div class="delKuangBody">
        <Form
          ref="form"
          :model="formItem"
          :label-width="80"
          :rules="formItemRule"
        >
          <FormItem label="服务名称" prop="serviceName">
            <Input
              v-model="formItem.serviceName"
              placeholder="请输入节点名称"
            ></Input>
          </FormItem>
          <FormItem label="服务类型" prop="clusterServiceType.id">
            <Select v-model="formItem.clusterServiceType.id">
              <template v-for="item in selcetData.type">
                <Option :value="item.id" :key="item.id">{{
                  item.description
                }}</Option>
              </template>
            </Select>
          </FormItem>

          <FormItem label="服务描述">
            <Input
              v-model="formItem.description"
              placeholder="请输入内容"
            ></Input>
          </FormItem>

          <FormItem label="依赖服务">
            <Select multiple v-model="formItem.relations">
              <template v-for="item in selcetData.relations">
                <Option :value="item.id" :key="item.id">{{
                  item.serviceName
                }}</Option>
              </template>
            </Select>
          </FormItem>


          <FormItem label="包含资源">
            <Select multiple v-model="formItem.resources">
              <template v-for="item in selcetData.resources">
                <Option :value="item.id" :key="item.id">{{
                  item.resourceAlias
                }}</Option>
              </template>
            </Select>
          </FormItem>



        </Form>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="handleReset" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="checkTaskOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
  </div>
</template>

<script>
import TableList from "@/template/table/TableList";

export default {
  name: "serviceManagement",
  components: { TableList },
  data() {
    const isselect = (rule,value,callback)=>{
      if(value){
        callback
      }else{
        return callback(new Error("请输入服务类型"))
      }
    }
    return {
      
      formItemRule: {
        "clusterServiceType.id":{
          type: 'number',
           required: true,
          message: "请输入服务类型",
          // trigger: "change",
          validate:"isselect"
        },
        serviceName: {
          required: true,
          message: "请输入服务名称",
          trigger: "blur",
        },
      },
      formItem: {
        serviceName: "",
        clusterServiceType: { id: "" },
        description: "",
        relations: [],
        resources: [],
      },







      name: "",
      getColumns: [
        {
          title: "服务名称",
          key: "serviceName",
          className: "centerText",
        },

        {
          title: "服务类型",
          key: "type",
          className: "centerText",
          align: "center",
          slot: "type",
        },
        {
          title: "服务描述",
          key: "description",
          align: "center",
          className: "centerText",
        },

        {
          title: "依赖服务",
          key: "relations",
          className: "centerText",
          align: "center",
          slot: "relations",
        },
        {
          title: "包含资源",
          key: "resources",
          className: "centerText",
          align: "center",
          slot: "resources",
        },
        {
          title: "创建时间",
          key: "createTime",
          className: "centerText",
          width: "220",
          align: "center",
        },
        {
          title: "更新时间",
          key: "createTime",
          className: "centerText",
          width: "220",
          align: "center",
        },

        {
          key: "show_details",
          slot: "show_details",
          title: "操作",
          align: "center",
          width: "180",
        },
      ],
      getAxios: {
        url: this.$api.monitorApi.getServiceLis, //请求路径
        method: "get", //请求方式
        dataList: {}, //请求参数
      },
      checkTask: false,
      selcetData: {
        type: [],
        relations: [],
        resources: [],
      },
    };
  },

  computed: {


  },



  mounted() {
    this.getServeType();
  },
  methods: {
    getServeType() {
      let that = this;
      // 类型
      this.http.get(this.$api.monitorApi.type).then((res) => {
        if (res.data.success) {
          that.selcetData.type = res.data.data;
        }
      });
      // 服务列表
      this.http.get(this.$api.monitorApi.getServiceLis).then((res) => {
        if (res.data.success) {
          that.selcetData.relations = res.data.data.serviceList;
        }
      });
      // 资源
      this.http.get(this.$api.monitorApi.getResourceList).then((res) => {
        if (res.data.success) {
          that.selcetData.resources = res.data.data.resourceList;
        }
      });
    },

    getResources(row, lab, name) {
      let list = "";   
       console.log(row[lab],'woshi niyaozhaode')
   list =   row[lab].map((item,index) => {

 
  //  row[lab].forEach((item) => {
  //       list += item[name] + "  ";
        if(row[lab].length - 1 == index){
          return item[name]
        }else{
            return item[name] + "";
        }
       
      });
  // return list;
      return list.toString();
    },
    delectRow(row) {
      let that = this;
      this.$Modal.confirm({
        title: "删除",
        content: "<p>请确认是否删除当前服务？</p>",
        loading: true,
        onOk: () => {
          that.http
            .delete(this.$api.monitorApi.delectService + row.id)
            .then((res) => {
              if (res.data.success) {
                that.$Message.info("删除成功！");
                that.$refs.table.getRefreshTable({});
              } else {
                that.$Message.info("删除失败！");
              }
              that.$Modal.remove();
            })
            .catch((err) => {
              that.$Message.info(err);
              that.$Modal.remove();
            });
        },
      });
    },
    searchList() {
      this.$refs.table.getRefreshTable({ name: this.name });
    },

    addServe() {
      this.checkTask = true;
      this.clearForm();
    },
    changeServe(data) {
      this.checkTask = true;
      let newForm = JSON.parse(JSON.stringify(data));
      let objToArr = function (data) {
        let arr = [];
        data.forEach((item) => {
          arr.push(item.id);
        });
        return arr;
      };
      newForm.relations = objToArr(newForm.relations);
      newForm.resources = objToArr(newForm.resources);
      this.formItem = newForm;
    },

    clearForm() {
      this.formItem = {
        serviceName: "",
        clusterServiceType: { id: "" },
        description: "",
        relations: [],
        resources: [],
      };
    },

    newFormData() {
      let newForm = JSON.parse(JSON.stringify(this.formItem));
      let relationsArr = [];
      let resourcesArr = [];
      this.formItem.relations.forEach((item)=>{
        relationsArr.push({id: item})
      })

      let idList = new Set();
      let disableConfim = true;

      let data = this.selcetData.resources.filter((item) => {
        if (  this.formItem.resources.includes(item.id)  ) {
          if (idList.has(item.clusterResourceType.id)) {
            disableConfim = false;
            this.$Message.info("不能选择资源类型相同的资源,请重新选择！");
            // item.resourceAlias
            return false;
          } else {
            idList.add(item.clusterResourceType.id);
            return true;
          }
        }else{
          return false;
        }
      });

      data.forEach((item)=>{
        resourcesArr.push( {"clusterResourceType": {"id": item.clusterResourceType.id}, "id":item.id});
      })
      newForm.relations = relationsArr;
      newForm.resources = resourcesArr;

      if (disableConfim) {
        return newForm
      }else {
        return false;
      }

    },


    checkTaskOk() {
      let that = this;
      this.$refs.form.validate((valid) => {
        if (valid) {

          let params = that.newFormData();
          if (!params) return;
          that.http[params.id ? "put" : "post"](
            params.id
              ? this.$api.monitorApi.upService + params.id
              : this.$api.monitorApi.service,
            params
          ).then((res) => {
            if (res.data.success) {
              params.id
                ? that.$Message.success("更新成功!")
                : that.$Message.success("创建成功!");
              that.checkTask = false;
              that.clearForm();
              that.$refs.table.getRefreshTable();
            } else {
              that.$Message.info("创建失败!");
            }
          });
        } else {
          this.$Message.error("请完成表单！");
        }
      });
    },
    handleReset() {
      this.checkTask = false;
      this.clearForm();
    },
  },
};
</script>

<style scoped>
.rightCard {
  width: 80%;
  flex: 1;
}

.leftCard {
  width: 18%;
}
/deep/.card {
  margin-bottom: 0;
}
.headerMar {
  margin-left: 10px;
}
</style>
